#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ddebug.h"

#define RECV_MAX 1000
int main(int argc, char *argv[])
{
	char command[20];
	char recv_buf[RECV_MAX];
	command[19] = 0;
	int sockfd;
	int len;
	int recv_len;
	int send_len;
	struct sockaddr_in serveraddr = {0};

	if(3 != argc)
	{
		printf("Usage: %s <IP> <PORT>\n", argv[0]);
		return -1;
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == sockfd)
		syserr("socket");

	serveraddr.sin_family  = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);

	len = sizeof serveraddr;

	if(-1 == connect(sockfd, (struct sockaddr*)&serveraddr, len))
		syserr("connect");

	while(1)
	{
		read(sockfd, &recv_len, sizeof(int));
		while(recv_len > 0)
		{
			if(recv_len < RECV_MAX)
			{
				read(sockfd, recv_buf, recv_len);
				write(1, recv_buf, recv_len);
				break;
			}
			read(sockfd, recv_buf, RECV_MAX);
			write(1, recv_buf, RECV_MAX);
			recv_len -= RECV_MAX;
		}
		fgets(command, 19, stdin);
		if(18 == strlen(command))
			while('\n' != getchar());
	//	printf("%d\n", strlen(command));
		if(strncmp(command, "quit", 4) == 0)
			break;
		DDEBUG(D_URGENCY, "send:%d\n",strlen(command));
		command[strlen(command)-1] = 0;
		send_len = strlen(command) + 1;
		send(sockfd, &send_len, 4, 0);
		send(sockfd, command, send_len, 0);
	//	printf("send:%s\n",command);
	}
	return 0;
}
